"use strict";

import Vue from 'vue';
import axios from "axios";
import VuexStore from "@/store/index"

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL:"http://47.115.51.185/api",
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // 在ajax请求发起之前,判断本地有没有token数据,如果有,则每次带上token
    let token = VuexStore.getters.logintoken;
    if(token && token.length > 1){
      config.headers = {
        "Authori-zation": "Bearer " + token 
      }
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

////响应拦截器
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    if(response.data){
      if(response.data.data){
        return response.data.data;
      }
      return response.data;
    }
    return response;
  },
  function(error) {
    // 如果响应失败，创建一个失败的Promise对象，并添加错误信息
    return Promise.reject(error);
  }
);


Plugin.install = function(Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default _axios;
